<template>
  <view class="evaluate-page" :style="{
    '--primary-color': themeColorStyles.primaryColor,
    '--primary-color-bg': themeColorStyles.primaryColorBg,
    '--primary-color-border': themeColorStyles.primaryColorBorder,
    '--primary-color-shadow': themeColorStyles.primaryColorShadow,
    '--primary-color-dark': themeColorStyles.primaryColorDark
  }">


    <scroll-view class="content-scroll" scroll-y>


      <!-- 多维度评分卡片 -->
      <view class="rating-card">
        <view class="card-header">
          <text class="card-title">商品评分</text>
          <text class="card-subtitle">请为各项服务打分</text>
        </view>
        <view class="rating-sections">
          <view 
            class="rating-item" 
            v-for="(item, index) in ratingItems" 
            :key="item.key"
            :style="{ 'animation-delay': index * 0.1 + 's' }"
          >
            <view class="rating-label">
              <text class="label-icon">{{ item.icon }}</text>
              <text class="label-text">{{ item.label }}</text>
            </view>
            <view class="rating-stars">
              <view 
                class="star-item" 
                v-for="(star, starIndex) in 5" 
                :key="starIndex"
                @click="setRating(item.key, starIndex + 1)"
                :style="{ 'animation-delay': (index * 5 + starIndex) * 0.05 + 's' }"
              >
                <text 
                  class="star-icon" 
                  :class="{ 
                    'active': starIndex < ratings[item.key],
                    'bounce': starIndex === ratings[item.key] - 1 && animatingRating === item.key
                  }"
                >★</text>
              </view>
            </view>
            <text class="rating-score">{{ ratings[item.key] }}.0</text>
          </view>
        </view>
        <view class="overall-rating">
          <text class="overall-label">综合评分</text>
          <text class="overall-score">{{ overallRating.toFixed(1) }}</text>
          <text class="overall-text">{{ getOverallRatingText(overallRating) }}</text>
        </view>
      </view>

      <!-- 评价内容卡片 -->
      <view class="content-card">
        <view class="card-header">
          <text class="card-title">评价内容</text>
          <text class="card-subtitle">分享您的使用体验</text>
        </view>
        <view class="textarea-wrapper">
          <textarea 
            class="evaluate-textarea"
            v-model="evaluateContent"
            placeholder="请详细描述您对商品的评价，帮助其他买家了解商品质量..."
            maxlength="500"
            :show-confirm-bar="false"
          ></textarea>
          <view class="char-count">
            <text class="count-text">{{ evaluateContent.length }}/500</text>
          </view>
        </view>
      </view>

      <!-- 图片上传卡片 -->
      <view class="upload-card">
        <view class="card-header">
          <text class="card-title">上传图片</text>
          <text class="card-subtitle">最多上传9张图片</text>
        </view>
        <view class="upload-grid">
          <view 
            class="upload-item"
            v-for="(image, index) in uploadedImages"
            :key="index"
          >
            <image class="uploaded-image" :src="image" mode="aspectFill"></image>
            <view class="delete-btn" @click="deleteImage(index)">
              <text class="delete-icon">×</text>
            </view>
          </view>
          <view 
            class="upload-btn"
            v-if="uploadedImages.length < 9"
            @click="chooseImage"
          >
            <text class="upload-icon">📷</text>
            <text class="upload-text">添加图片</text>
          </view>
        </view>
      </view>



      <!-- 底部间距 -->
      <view class="bottom-space"></view>
    </scroll-view>

    <!-- 底部操作栏 -->
    <view class="footer-actions">
      <view class="submit-btn" @click="submitEvaluate">
        <text class="btn-text">提交评价</text>
      </view>
    </view>
  </view>
</template>

<script>
import { submitComment, checkCommentStatus, uploadCommentImage } from '@/api/order'
import { API_CONFIG } from '@/api/config'
import { getToken } from '@/utils/auth'
import { checkLoginStatus, handleApiError } from '@/utils/loginCheck'
import themeColorMixin from '@/mixins/themeColorMixin'

export default {
  mixins: [themeColorMixin],
  data() {
    return {
      orderId: '',
      productId: '',
      productInfo: {
        id: 1,
        name: '时尚休闲T恤',
        spec: '白色 L码',
        price: '99.00',
        image: '/static/images/product1.jpg'
      },
      ratings: {
        product: 5,
        service: 5,
        logistics: 5,
        packaging: 5
      },
      animatingRating: '',
      ratingItems: [
        { key: 'product', label: '商品质量', icon: '📦' },
        { key: 'service', label: '服务态度', icon: '👥' },
        { key: 'logistics', label: '物流速度', icon: '🚚' },
        { key: 'packaging', label: '包装质量', icon: '📋' }
      ],
      evaluateContent: '',
      uploadedImages: [],
      uploadedImagePaths: [] // 存储上传后的图片路径
    }
  },
  
  computed: {
    // 计算综合评分
    overallRating() {
      const values = Object.values(this.ratings);
      const sum = values.reduce((acc, val) => acc + val, 0);
      return sum / values.length;
    }
  },
  
  onLoad(options) {
    if (options.orderId) {
      this.orderId = options.orderId;
    }
    if (options.productId) {
      this.productId = options.productId;
      this.loadProductInfo();
    }
    // 初始化主题色
    this.initThemeColor();
  },
  
  methods: {
    // 返回上一页
    goBack() {
      uni.navigateBack();
    },
    
    // 加载商品信息
    loadProductInfo() {
      // 这里可以根据productId调用API获取商品信息
      // console.log('加载商品信息:', this.productId);
    },
    
    // 设置评分
    setRating(key, score) {
      this.ratings[key] = score;
      this.animatingRating = key;
      
      // 添加动画效果
      setTimeout(() => {
        this.animatingRating = '';
      }, 300);
      
      // 添加震动反馈
      uni.vibrateShort();
    },
    
    // 获取综合评分文本
    getOverallRatingText(rating) {
      if (rating >= 4.5) return '非常满意';
      if (rating >= 3.5) return '满意';
      if (rating >= 2.5) return '一般';
      if (rating >= 1.5) return '不满意';
      return '很不满意';
    },
    
    // 选择图片
    chooseImage() {
      const remainCount = 9 - this.uploadedImages.length;
      uni.chooseImage({
        count: remainCount,
        sizeType: ['compressed'],
        sourceType: ['album', 'camera'],
        success: (res) => {
          // 显示本地图片
          this.uploadedImages = this.uploadedImages.concat(res.tempFilePaths);
          
          // 上传图片到服务器
          res.tempFilePaths.forEach(tempPath => {
            this.uploadImage(tempPath);
          });
        }
      });
    },
    
    // 删除图片
    deleteImage(index) {
      this.uploadedImages.splice(index, 1);
    },
    
    // 上传单张图片
    async uploadImage(tempPath) {
      try {
        uni.showLoading({
          title: '上传中...'
        });
        
        // 使用uni.uploadFile上传图片
        uni.uploadFile({
          url: API_CONFIG.BASE_URL + '/app/order/comment/upload',
          filePath: tempPath,
          name: 'file',
          header: {
            'Authorization': 'Bearer ' + getToken()
          },
          success: (response) => {
            // console.log('上传响应:', response);
            
            if (!response.data) {
              // console.error('服务器响应为空');
              uni.showToast({
                title: '服务器响应为空',
                icon: 'none'
              });
              return;
            }
            
            // 检查响应数据是否为有效JSON
            let result;
            try {
              result = JSON.parse(response.data);
            } catch (parseError) {
              // console.error('JSON解析失败:', parseError, '响应数据:', response.data);
              uni.showToast({
                title: '服务器响应格式错误',
                icon: 'none'
              });
              return;
            }
            
            if (result.code === 200) {
              this.uploadedImagePaths.push(result.data.url);
              // console.log('图片上传成功，路径:', result.data.url);
              // console.log('当前uploadedImagePaths:', this.uploadedImagePaths);
              uni.showToast({
                title: '图片上传成功',
                icon: 'success'
              });
            } else {
              uni.showToast({
                title: result.msg || '图片上传失败',
                icon: 'none'
              });
            }
          },
          fail: (error) => {
            // console.error('上传失败:', error);
            uni.showToast({
              title: '网络错误，上传失败',
              icon: 'none'
            });
          },
          complete: () => {
            uni.hideLoading();
          }
        });
        
      } catch (error) {
        uni.hideLoading();
        // console.error('上传图片失败:', error);
        uni.showToast({
          title: '图片上传失败',
          icon: 'none'
        });
      }
    },
    

    
    // 提交评价
    async submitEvaluate() {
      // 使用统一的登录检测
      const loginResult = await checkLoginStatus()
      if (!loginResult.isLoggedIn) {
        return
      }
      
      // 检查评价内容
      if (this.evaluateContent.trim().length < 10) {
        uni.showToast({
          title: '评价内容至少10个字',
          icon: 'none'
        });
        return;
      }
      
      // 计算综合评分（取商品质量评分作为主要评分）
      const star = this.ratings.product;
      
      uni.showLoading({
        title: '提交中...'
      });
      
      try {
        // 构建评价数据
        const commentData = {
          orderId: this.orderId,
          productId: this.productId,
          star: star,
          content: this.evaluateContent.trim(),
          images: this.uploadedImagePaths.join(',') // 用逗号分隔的图片路径
        };
        
        // console.log('提交评价数据:', commentData);
        // console.log('图片路径数组:', this.uploadedImagePaths);
        // console.log('拼接后的图片字符串:', this.uploadedImagePaths.join(','));
        
        // 调用API提交评价
        const response = await submitComment(commentData);
        
        uni.hideLoading();
        
        if (response.code === 200) {
          uni.showToast({
            title: '评价提交成功',
            icon: 'success'
          });
          
          // 返回上一页
          setTimeout(() => {
            uni.navigateBack();
          }, 1500);
        } else {
          uni.showToast({
            title: response.msg || '提交失败',
            icon: 'none'
          });
        }
        
      } catch (error) {
        uni.hideLoading();
        // console.error('提交评价失败:', error);
        await handleApiError(error);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.evaluate-page {
  background: linear-gradient(180deg, #F8FAFE 0%, #F2F6FC 100%);
  min-height: 100vh;
  padding-bottom: 120rpx;
}



/* 内容滚动区域 */
.content-scroll {
  height: calc(100vh - 120rpx);
  padding: 32rpx;
}

/* 卡片基础样式 */

.rating-card {
  background: #FFFFFF;
  border-radius: 24rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  overflow: hidden;
  animation: slideInUp 0.6s ease-out 0.2s both;
  transition: all 0.3s ease;
}

.content-card {
  background: #FFFFFF;
  border-radius: 24rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  overflow: hidden;
  animation: slideInUp 0.6s ease-out 0.3s both;
  transition: all 0.3s ease;
}

.upload-card {
  background: #FFFFFF;
  border-radius: 24rpx;
  margin-bottom: 32rpx;
  box-shadow: 0 4rpx 20rpx rgba(0, 0, 0, 0.06);
  overflow: hidden;
  animation: slideInUp 0.6s ease-out 0.4s both;
  transition: all 0.3s ease;
}



.card-header {
  padding: 32rpx 32rpx 24rpx;
  border-bottom: 1px solid #F5F7FA;
}

.card-title {
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
  display: block;
  margin-bottom: 8rpx;
}

.card-subtitle {
  font-size: 28rpx;
  color: #8B9BB0;
}




/* 多维度评分卡片 */
.rating-sections {
  padding: 32rpx;
}

.rating-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 24rpx 0;
  border-bottom: 1px solid #F5F7FA;
  animation: slideInUp 0.6s ease-out both;
  
  &:last-child {
    border-bottom: none;
  }
}

.rating-label {
  display: flex;
  align-items: center;
  flex: 1;
}

.label-icon {
  font-size: 32rpx;
  margin-right: 16rpx;
}

.label-text {
  font-size: 30rpx;
  font-weight: 500;
  color: #1A1A1A;
}

.rating-stars {
  display: flex;
  margin: 0 24rpx;
}

.star-item {
  margin: 0 4rpx;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  animation: fadeInScale 0.4s ease-out both;
  
  &:active {
    transform: scale(1.3);
  }
}

.star-icon {
  font-size: 40rpx;
  color: #E5E7EB;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  
  &.active {
    color: var(--primary-color);
    text-shadow: 0 0 10rpx var(--primary-color-shadow);
  }
  
  &.bounce {
    animation: starBounce 0.6s ease-out;
  }
}

.rating-score {
  font-size: 28rpx;
  font-weight: 600;
  color: var(--primary-color);
  min-width: 60rpx;
  text-align: center;
}

.overall-rating {
  margin-top: 32rpx;
  padding: 24rpx;
  background: linear-gradient(135deg, #F8FAFE 0%, #E8F2FF 100%);
  border-radius: 16rpx;
  display: flex;
  align-items: center;
  justify-content: space-between;
  animation: slideInUp 0.8s ease-out both;
}

.overall-label {
  font-size: 32rpx;
  font-weight: 600;
  color: #1A1A1A;
}

.overall-score {
  font-size: 48rpx;
  font-weight: 700;
  color: var(--primary-color);
  text-shadow: 0 2rpx 4rpx var(--primary-color-shadow);
}

.overall-text {
  font-size: 28rpx;
  color: var(--primary-color);
  font-weight: 500;
}



/* 评价内容卡片 */
.textarea-wrapper {
  padding: 32rpx;
  position: relative;
}

.evaluate-textarea {
  width: 100%;
  min-height: 200rpx;
  padding: 24rpx;
  border: 2rpx solid #E5E7EB;
  border-radius: 16rpx;
  font-size: 30rpx;
  color: #1A1A1A;
  background: #FAFBFC;
  box-sizing: border-box;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  
  &:focus {
    border-color: var(--primary-color);
    background: #FFFFFF;
    box-shadow: 0 0 0 4rpx var(--primary-color-bg);
    transform: translateY(-2rpx);
  }
}

.char-count {
  position: absolute;
  bottom: 48rpx;
  right: 48rpx;
}

.count-text {
  font-size: 24rpx;
  color: #8B9BB0;
}

/* 图片上传卡片 */
.upload-grid {
  padding: 32rpx;
  display: flex;
  flex-wrap: wrap;
  gap: 16rpx;
}

.upload-item {
  width: 160rpx;
  height: 160rpx;
  position: relative;
  border-radius: 16rpx;
  overflow: hidden;
}

.uploaded-image {
  width: 100%;
  height: 100%;
}

.delete-btn {
  position: absolute;
  top: 8rpx;
  right: 8rpx;
  width: 48rpx;
  height: 48rpx;
  border-radius: 50%;
  background: rgba(0, 0, 0, 0.6);
  display: flex;
  align-items: center;
  justify-content: center;
}

.delete-icon {
  font-size: 32rpx;
  color: #FFFFFF;
  font-weight: bold;
}

.upload-btn {
  width: 160rpx;
  height: 160rpx;
  border: 2rpx dashed #C1C9D2;
  border-radius: 16rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  background: #FAFBFC;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  animation: pulse 2s infinite;
  
  &:active {
    background: #F0F4F8;
    transform: scale(0.95);
    animation: none;
  }
  
  &:hover {
    border-color: var(--primary-color);
    background: var(--primary-color-bg);
  }
}

.upload-icon {
  font-size: 48rpx;
  margin-bottom: 8rpx;
}

.upload-text {
  font-size: 24rpx;
  color: #8B9BB0;
}



/* 底部操作栏 */
.footer-actions {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background: #FFFFFF;
  padding: 24rpx 32rpx;
  box-shadow: 0 -4rpx 20rpx rgba(0, 0, 0, 0.06);
  z-index: 100;
}

.submit-btn {
  width: 100%;
  height: 96rpx;
  border-radius: 48rpx;
  background: var(--primary-color);
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
  box-shadow: 0 4rpx 20rpx var(--primary-color-shadow);
  position: relative;
  overflow: hidden;
  
  &::before {
    content: '';
    position: absolute;
    top: 0;
    left: -100%;
    width: 100%;
    height: 100%;
    background: linear-gradient(90deg, transparent, rgba(255, 255, 255, 0.2), transparent);
    transition: left 0.6s ease;
  }
  
  &:active {
    background: var(--primary-color-dark);
    transform: scale(0.98);
    box-shadow: 0 2rpx 10rpx var(--primary-color-shadow);
    
    &::before {
      left: 100%;
    }
  }
}

.btn-text {
  font-size: 32rpx;
  font-weight: 600;
  color: #FFFFFF;
}

.bottom-space {
  height: 40rpx;
}

/* 动画关键帧 */
@keyframes slideInUp {
  from {
    opacity: 0;
    transform: translateY(30rpx);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

@keyframes fadeInScale {
  from {
    opacity: 0;
    transform: scale(0.8);
  }
  to {
    opacity: 1;
    transform: scale(1);
  }
}

@keyframes starBounce {
  0%, 20%, 50%, 80%, 100% {
    transform: translateY(0);
  }
  40% {
    transform: translateY(-10rpx);
  }
  60% {
    transform: translateY(-5rpx);
  }
}

@keyframes pulse {
  0% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.05);
  }
  100% {
    transform: scale(1);
  }
}
</style>